﻿using MCMesServer.NetConnectFunc;
using MCMesServer.PublicLogInfo;
using MesDAL.DTO.ProcessSheet;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MCMesServer.WorkMessageSaveFunc
{
    public class WorkPieceImageSaveFunc
    {
        /// <summary>
        /// 将byte数组转为图片
        /// </summary>
        /// <param name="array"></param>
        /// <returns></returns>
        public static Image ConvertByte2Image(byte[] array)
        {
            try
            {
                if (array is null)
                {
                    return null;
                }
                else
                {
                    Image image = new Bitmap(new MemoryStream(array));
                    return image;
                }
            }
            catch (Exception ex)
            {
                PublicLogInfoFunc.RecordManualErrorMessage("将Byte数组转为图片", $"{ex.ToString()}");
                return null;
            }
        }

        /// <summary>
        /// 将图片转为byte数组
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        public static byte[] ConvertImage2ByteArray(Image bitmap)
        {
            try
            {
                if (bitmap is null)
                {
                    return null;
                }
                else
                {
                    using (var ms = new MemoryStream())
                    {
                        bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                        return ms.ToArray();
                    }
                }
            }
            catch (Exception ex)
            {
                PublicLogInfoFunc.RecordManualErrorMessage("将图片转为byte数组", ex.ToString());
                return null;
            }
        }

        /// <summary>
        /// 将图片保存至指定位置
        /// </summary>
        /// <param name="imageName"></param>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        public static string SaveImageIntoServer(string imageName, Image bitmap)
        {
            try
            {
                string CommonPath = ConfigClass.ReadIniData("SaveImagePath", "Path", MainWindow.ConfigPath);
                string bitmapPath = CommonPath + "\\" + imageName + "\\" + imageName + ".png";
                lock (new object())
                {
                    Directory.CreateDirectory(CommonPath + "\\" + imageName);
                    using (var stream = new FileStream(bitmapPath, FileMode.Create))
                    {
                        bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                    }
                }
                return bitmapPath;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return null;
            }
        }
    }
}
